﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using IM.Easy.Core.Utils;

namespace IM.Easy.Core.Filters
{
    public class GlobalAuthorizeFilter : IAsyncAuthorizationFilter
    {
        public virtual async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            var endpoint = context.HttpContext.GetEndpoint();
            var allowAnonymous = endpoint?.Metadata.GetMetadata<IAllowAnonymous>() != null;

            if (!allowAnonymous)
            {
                var result = await context.HttpContext.AuthenticateAsync();
                if (!result.Succeeded)
                {
                    ExceptionUtils.ThrowUnauthorized();
                }
            }

        }
    }
}
